package link.cocoon.security.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 用于统计请求耗时，并报错慢请求。
 *
 * @author xce
 * @date 2019/10/18 16:27
 */
@Component
@Slf4j
public class TimerFilter implements Filter {

  private static final long THRESHOLD = 500;

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    log.info("init TimerFilter");
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String uri = ((HttpServletRequest) request).getRequestURI();
    long start = System.currentTimeMillis();
    chain.doFilter(request, response);
    long useTime = System.currentTimeMillis() - start;
    if (useTime < THRESHOLD) {
      log.info("请求:{} {}  用时:{}ms", ((HttpServletRequest) request).getMethod(), uri,
          System.currentTimeMillis() - start);
      return;
    }
    log.error("请求耗时超过阈值{}ms", THRESHOLD);
    log.error("请求:{} {}  用时:{}ms", ((HttpServletRequest) request).getMethod(), uri, System.currentTimeMillis() - start);

  }
}
